import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Item {
    id: onlineMaterialListBack_ListWindow
    width: 1760
    height: 935

    Component.onCompleted: {
        Cpp_PLC.write_into_PLC_16_Hold(48,"3")
        Cpp_PLC.write_into_PLC_Coils(142,true)
        onlineCutDataModel.readFromCsv(); // 加载上次保存的数据
    }

    Component.onDestruction: {
        onlineCutDataModel.saveToCsv()
    }


    property bool plc_M61: Cpp_PLC.M_61
    property bool plc_M96: Cpp_PLC.M_96
    property bool plc_M97: Cpp_PLC.M_97
    property bool plc_X13: Cpp_PLC.X13


    property real fontSize: Cpp_Language.CurrentLanguage === 1 ? 20 : Cpp_Language.CurrentLanguage === 2 ? 13 : Cpp_Language.CurrentLanguage === 3 ? 13 : 20

    Row {
        anchors.top: parent.top
        anchors.left: parent.left
        height: 50

        // 11个标题项（按文字长度分配宽度，总和=1500）
        TitleItem { title: qsTr("序号"); itemWidth: 90 }        // 1/11
        TitleItem { title: qsTr("订单编号"); itemWidth: 190 }   // 2/11
        TitleItem { title: qsTr("型材类型"); itemWidth: 170 }   // 3/11
        TitleItem { title: qsTr("产品名称"); itemWidth: 170 }   // 4/11
        TitleItem { title: qsTr("颜色"); itemWidth: 100 }         // 5/11
        TitleItem { title: qsTr("原料长度"); itemWidth: 130 }   // 6/11
        TitleItem { title: qsTr("切割长度"); itemWidth: 130 }   // 7/11
        TitleItem { title: qsTr("左角度"); itemWidth: 120 }     // 8/11
        TitleItem { title: qsTr("右角度"); itemWidth: 120 }     // 9/11
        TitleItem { title: qsTr("切割数量"); itemWidth: 140 }   // 10/11
        TitleItem { title: qsTr("已切数量"); itemWidth: 140 }   // 11/11
    }

    // 标题项组件（统一样式与布局）
    component TitleItem: Rectangle {
        property string title: ""       // 标题文本
        property real itemWidth: 100    // 单项宽度

        width: itemWidth
        height: parent.height  // 高度与容器一致（80）
        color: "#eeeeee"       // 标题项背景（略深于总背景）
        border.width: 0.5
        border.color: "#ddd"


        // 标题文字（自动适应宽度，防止溢出）
        Text {
            anchors.centerIn: parent
            text: title
            font.pixelSize: fontSize  // 适中字号，平衡显示与空间
            font.bold: true
            color: "#333"
            elide: Text.ElideRight  // 极端情况文字过长时省略尾部
            maximumLineCount: 1    // 强制单行显示
        }
    }


    // 表格项目
    ListView {
        id: listView
        anchors.top: parent.top
        anchors.topMargin: 50
        width: 1500
        height: 880
        // anchors.bottom: parent.bottom  // 与listArea底部绑定，高度自适应
        model: onlineCutDataModel
        clip: true
        // 禁用拖动超出边界的效果（到达边界后停止）
        boundsBehavior: Flickable.StopAtBounds


        Connections {
            target: onlineCutDataModel
            function onModelDataUpdated() {
                // 模型数据更新时，检查保存的索引是否仍有效
                if (Cpp_PLC.NetWork_CurrentIndex >= onlineCutDataModel.count) {
                    Cpp_PLC.NetWork_CurrentIndex = -1;  // 索引无效时重置
                }
                listView.currentIndex = -1;  // 保持原有逻辑：数据更新时取消选中
                console.log("模型数据更新，重置currentIndex");
            }
        }

        // 检查当前行是否完成
        function checkComplete(rowIndex) {
            if (rowIndex < 0 || rowIndex >= onlineCutDataModel.count) return false;
            const item = onlineCutDataModel.get(rowIndex);
            return item.cutCount === item.workedCount && item.cutCount !== 0;
        }

        // 查找下一个未完成的行（核心修改）
        function findNextValidRow(startIndex) {
            // 从startIndex+1开始查找
            for (let i = startIndex + 1; i < onlineCutDataModel.count; i++) {
                if (!checkComplete(i)) {
                    return i; // 返回第一个未完成的行索引
                }
            }
            return -1; // 未找到有效行
        }

        // 自动移动到下一个有效行（跳过已完成行）
        function moveToNextValidRow(currentIndex) {
            // 查找下一个未完成的行
            const nextIndex = findNextValidRow(currentIndex);

            if (nextIndex !== -1) {
                // 找到有效行，移动到该行
                listView.currentIndex = nextIndex;
                console.log("自动跳过已完成行，移动到第" + (nextIndex + 1) + "行");
            } else {
                // 未找到有效行，检查是否全部完成
                listView.currentIndex = -1;
                console.log("后续无有效行，取消选中");
                checkAndShowCompletionDialog();
            }
        }

        // 检查所有行是否都已完成
        function checkAllComplete() {
            if (onlineCutDataModel.count === 0) return false;
            for (let i = 0; i < onlineCutDataModel.count; i++) {
                if (!checkComplete(i)) {
                    return false;
                }
            }
            return true;
        }

        // 检查并显示完成弹窗
        function checkAndShowCompletionDialog() {
            if (checkAllComplete() && !completionDialogShown) {
                completionDialog.visible = true;
                completionDialogShown = true;
            }
        }

        onCurrentIndexChanged: {
            // 仅当currentIndex有效（>=0且在模型范围内）时执行PLC指令
            if (currentIndex >= 0 /*&& currentIndex < onlineCutDataModel.count*/) {

                Cpp_PLC.write_into_PLC_Coils(142,true)

                // 获取当前选中项的数据
                const currentItem = onlineCutDataModel.get(currentIndex);
                console.log("ListView换行，当前选中第" + (currentIndex + 1) + "行，执行PLC写入指令");

                console.log("写入 切割长度: "+currentItem.cutLength + " 左角度: "+currentItem.leftAngle + " 右角度: "+currentItem.rightAngle +" 切割数量: "+currentItem.cutCount)
                if(Number(currentItem.cutLength) < Number(Cpp_PLC.ExtraShort_MaterialLengthMin))
                {
                    Cpp_PLC.write_into_PLC_32_Hold(1440,currentItem.cutLength)
                }
                else if(Number(currentItem.cutLength) > Number(Cpp_PLC.ExtraLong_MaterialLengthMax))
                {
                    Cpp_PLC.write_into_PLC_32_Hold(1440,currentItem.cutLength)
                }
                else
                {
                    Cpp_PLC.write_into_PLC_32_Hold(1440,currentItem.cutLength)
                }

                if(currentItem.leftAngle === 45)
                {
                    Cpp_PLC.write_into_PLC_16_Hold(1520,"0");
                }
                else if(currentItem.leftAngle === 90)
                {
                    Cpp_PLC.write_into_PLC_16_Hold(1520,"1");
                }

                if(currentItem.rightAngle === 45)
                {
                    Cpp_PLC.write_into_PLC_16_Hold(1521,"0");
                }
                else if(currentItem.rightAngle === 90)
                {
                    Cpp_PLC.write_into_PLC_16_Hold(1521,"1");
                }

                Cpp_PLC.write_into_PLC_16_Hold(1480,currentItem.cutCount)
                // 当前数量写入 D66
                Cpp_PLC.write_into_PLC_16_Hold(66,currentItem.cutCount)
                // 当前已加工数量 写入 D231
                Cpp_PLC.write_into_PLC_16_Hold(231,currentItem.workedCount)

                Cpp_PLC.write_into_PLC_16_Hold(76,"1")
                // Cpp_PLC.write_into_PLC_Coils(172,0)
                if(Cpp_PLC.MechineChangeAngleMode)
                {
                    Cpp_PLC.write_into_PLC_Coils(140,1)
                    Cpp_PLC.write_into_PLC_Coils(141,1)
                }
                else
                {
                    Cpp_PLC.write_into_PLC_Coils(140,1)
                    Cpp_PLC.write_into_PLC_Coils(141,1)
                    Cpp_PLC.write_into_PLC_Coils(140,0)
                    Cpp_PLC.write_into_PLC_Coils(141,0)
                }

            } else {
                console.log("无有效选中项，不执行PLC写入");
            }
        }

        delegate:
            Item {
            // id: name
            width: listView.width  // 宽度绑定到ListView
            height: 44
            // 绑定模型属性到本地，用于监听变化
            property int currentWorkedCount: workedCount
            property int currentCutCount: cutCount
            property int currentIndex: index

            // 监听已切数量变化
            onCurrentWorkedCountChanged: {
                checkCompletion();
            }

            // 监听切割数量变化
            onCurrentCutCountChanged: {
                checkCompletion();
            }

            // 检查完成逻辑（添加自动换行开关控制）
            function checkCompletion() {
                if (currentCutCount === currentWorkedCount && currentCutCount !== 0) {
                    console.log("第" + (currentIndex + 1) + "行已完成");
                    if (listView.currentIndex === currentIndex) {
                        // 核心修改：只有启用自动换行时才执行自动移动
                        if (autoWrapEnabled) {
                            listView.moveToNextValidRow(currentIndex);
                        } else {
                            console.log("自动换行已禁用，保持当前选中状态");
                        }
                    }
                    listView.checkAndShowCompletionDialog();
                }
            }

            Row {
                id: dataRow
                height: parent.height

                // 序号列
                Rectangle {
                    width: 90
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: (currentIndex + 1)
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 订单编号列
                Rectangle {
                    width: 190
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"

                    Text {
                        id: orderCodeText
                        anchors.centerIn: parent
                        text: orderCode
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 型材类型列
                Rectangle {
                    width: 170
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"

                    Text {
                        id: profileTypeText
                        anchors.centerIn: parent
                        text: profileType
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }

                }

                // 产品名称列
                Rectangle {
                    width: 170
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"

                    Text {
                        id: productNameText
                        anchors.centerIn: parent
                        text: productName
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }

                }

                // 颜色列（宽度调整为140）
                Rectangle {
                    width: 100
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"

                    Text {
                        id: colorText
                        anchors.centerIn: parent
                        text: materialcolor
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8  // 适应更宽的列，提供更多显示空间
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 原料长度列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: materialLength
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 切割长度列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: cutLength.toFixed(2)
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 左角度列
                Rectangle {
                    width: 120
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: leftAngle + "°"
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 右角度列
                Rectangle {
                    width: 120
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: rightAngle + "°"
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 切割数量列
                Rectangle {
                    width: 140
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: currentCutCount
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 已切数量列
                Rectangle {
                    width: 140
                    height: parent.height
                    color: (currentCutCount === currentWorkedCount && currentCutCount !== 0) ? "#ffcccc"
                                                                                             : (listView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: currentWorkedCount
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }
            }

            MouseArea {
                width: dataRow.width
                height: dataRow.height
                onClicked: {
                    // 点击时如果是已完成行则不选中，否则正常选中
                    if (!listView.checkComplete(currentIndex)) {
                        listView.currentIndex = currentIndex;
                        console.log("选中第" + (currentIndex + 1) + "行");
                    } else {
                        console.log("第" + (currentIndex + 1) + "行已完成，不允许选中");
                    }
                }
            }

        }

        // 滚动条（确保能控制完整滚动）
        ScrollBar.vertical: ScrollBar {
            policy: ScrollBar.AlwaysOn
            // 绑定滚动条到ListView的可视区域和内容区域
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            anchors.right: parent.right
        }

        // 监听模型数据更新，重置选中状态
        Connections {
            target: onlineCutDataModel
            function onModelDataUpdated() {
                listView.currentIndex = -1;
                console.log("Model数据已更新，取消选中状态（currentIndex = -1）");
            }
        }
    }


    onPlc_X13Changed: {
        if((plc_M96 && plc_X13) || (plc_M97 && plc_X13))
        {
            //计数+1
            // console.log("计数加1！！！！！")
            const isComplete = materialListView.checkComplete(materialListView.currentIndex);
            if (isComplete) {
                console.log("第" + (materialListView.currentIndex + 1) + "行已完成，不更新已切数量");
                return;
            }
            onlineCutDataModel.incrementWorkedCount(materialListView.currentIndex);
            var updatedItem = onlineCutDataModel.get(materialListView.currentIndex);
            console.log("已更新第" + (materialListView.currentIndex + 1) + "项，已切数量：" + updatedItem.workedCount);
            // materialListView.checkAndShowCompletionDialog();
        }
        else
        {
            console.log("无有效选中项，不更新已切数量");
        }
    }

    onPlc_M61Changed: {
        if(plc_M61)
        {
            const isComplete = materialListView.checkComplete(materialListView.currentIndex);
            if (isComplete) {
                console.log("第" + (materialListView.currentIndex + 1) + "行已完成，不更新已切数量");
                return;
            }
            onlineCutDataModel.incrementWorkedCount(materialListView.currentIndex);
            var updatedItem = onlineCutDataModel.get(materialListView.currentIndex);
            console.log("已更新第" + (materialListView.currentIndex + 1) + "项，已切数量：" + updatedItem.workedCount);
        }
    }


    A_ComboBox{
        anchors.top: parent.top
        anchors.topMargin: 50
        anchors.right: parent.right
        comboBoxWidth: 240
        comboBoxHeight: 50

        currentIndex: Cpp_Config.Current_QR_Code === 6 ? 0
                    : Cpp_Config.Current_QR_Code === 7 ? 1
                    : Cpp_Config.Current_QR_Code === 8 ? 2
                    : Cpp_Config.Current_QR_Code === 9 ? 3
                                                       : -1


        model: [qsTr("长风在线"),
            qsTr("新格尔在线"),
            qsTr("速制在线"),
            qsTr("创品在线")]

        onComboBoxActivated: {
            console.log(currentText)
            // Cpp_Config.Current_QR_Code =
            if(currentIndex+1 === 1)
            {
                Cpp_Scanner.Current_QR_Type = 6
                Cpp_Config.Current_QR_Code = 6
            }
            else if(currentIndex+1 === 2)
            {
                Cpp_Scanner.Current_QR_Type = 7
                Cpp_Config.Current_QR_Code = 7
            }
            else if(currentIndex+1 === 3)
            {
                Cpp_Scanner.Current_QR_Type = 8
                Cpp_Config.Current_QR_Code = 8
            }
            else if(currentIndex+1 === 4)
            {
                Cpp_Scanner.Current_QR_Type = 9
                Cpp_Config.Current_QR_Code = 9
            }
        }
    }









}
